package com.zz.framework.core.ext.coroutine

import com.zz.framework.core.ext.coroutine.coroutineErrorListener
import com.zz.framework.core.ext.coroutine.exception.UncaughtCoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import java.io.Closeable
import kotlin.coroutines.CoroutineContext

/**
 *  CoroutineScope，支持异常处理
 */
class SafeCoroutineScope(context: CoroutineContext, errorHandler: coroutineErrorListener? = null) :
    CoroutineScope,
    Closeable {

    override val coroutineContext: CoroutineContext =
        SupervisorJob() + context + UncaughtCoroutineExceptionHandler(errorHandler)

    override fun close() {
        coroutineContext.cancelChildren()
    }
}